<template>
	<view :class="currentTheme">
		<a-nabbar :name="isEdit?'编辑剧本':'新增剧本'"/>
		<view class="u-padding-32">
			<view v-if="step==1">
				<!-- 第一步 -->
				<view class="box-title u-font-32 text-bold">剧本名称</view>
				<view  class="u-margin-top-32 u-position-relative">
					<u-input v-model="form.name" :customStyle="{...customStyle,padding:'10rpx 20rpx'}" :border="false" maxlength="20" :clearable="false" placeholder="请输入剧本名称" :placeholder-style="`color:${currentThemeObj.placeholderColor}`"/>
				</view>
				<view class="box-title u-font-32 u-margin-top-26 text-bold">编辑剧本简介</view>
				<view  class="u-margin-top-32 u-position-relative textarea-box">
					<u-input v-model="form.info" type="textarea" :border="false"  height="203" :auto-height="false" maxlength="300" :custom-style="customStyle" :clearable="false" :placeholder-style="`color:${currentThemeObj.placeholderColor}`"/>
					<view class="max-length-txt text-color-9598a4 u-font-28">
						{{form.info&&form.info.length || 0}}/300字
					</view>
				</view>
				<view class="u-flex u-row-between u-margin-bottom-26 u-margin-top-80">
					<text class="box-title u-font-32 text-bold">上传图片</text>
					<text class="u-font-28 text-tips">最多可上传6张</text>
				</view>
				<uploader ref="image" max-count="6" :bgColor="currentThemeObj.backgroundSecondColor" :list="form.sliderImage" v-if="showUpload" @getImgStr="getImgStr" @uploaded="getUpload"></uploader>
			</view>
			<view class=""  v-if="step==2">
				<!-- 第二步 -->
				<item-box padding="0">
					<view class="u-padding-left-40 u-padding-right-40">
						<label-box label="预计发布时间" labelWidth="190" labelSize="32" paddingTb="20">
							<select-item v-model="form.releaseTime" mode="time" placeholder="日期选择"></select-item>
						</label-box>
					</view>
				</item-box>
				<view v-for="(item,index) in secondStepList" :key="index" class="u-margin-top-20">
					<select-items :item="item" v-model="pushTypeChecked" :key="item.id" type="radio" @select="getpushType">
						<view class="u-font-32 box-title text-bold u-padding-bottom-24" slot="title">选择{{item.cateName}}</view>
					</select-items>
				</view>
				<view class="u-margin-top-20" v-if="isCityType">
					<view class="u-font-32 box-title text-bold u-padding-bottom-24">是否接受设置城市以外的意向</view>
					<item-box :padding="0">
						<select-items :item="acceptList" v-model="form.isAcceptCityOutside" type="radio"></select-items>
					</item-box>
					<view  class="u-margin-top-20">
						<view class="u-font-32 box-title text-bold u-padding-bottom-24">{{activeType.label}}城市选择</view>
						<item-box :padding="0">
							<view class="u-font-22 text-order-time u-text-center u-padding-top-38">点击下列标签修改</view>
							<u-row>
								<u-col span="4"  v-for="(c,i) in cityList" :key="i">
									<view class="u-margin-top-32 u-flex u-row-center">
										<cityBtn :item="c" @remove="removeItem" isEdit @select="select"></cityBtn>
									</view>
								</u-col>
							</u-row>
							<view class="u-margin-top-32 u-flex u-row-center" >
								<item-btn width="194" height="64" type="plain" borderColor="white"  @click="showCity = !showCity">
									<view class="u-flex">
										<text class="text-color-txtTheme u-font-26 u-margin-right-10">{{showCity?'收起':'显示全部'}}</text>
										<u-icon name="arrow-down" :color="currentThemeObj.primary" size="20"></u-icon>
									</view>
								</item-btn>
							</view>
							<view class="u-flex u-border-top u-margin-top-30">
								<view class="u-padding-top-30 u-padding-bottom-30 u-padding-left-20 u-padding-right-10 u-flex-1">
									<item-btn width="100%" height="88" @click="addCityPath"  type="plain">{{activeType.label}}编辑</item-btn>
								</view>
							</view>
						</item-box>
					</view>
				</view>
			</view>
			<template  v-if="step==3">
				<item-box padding="0">
					<view class="u-padding-left-40 u-padding-right-40">
						<label-box label="设置剧本人数" labelWidth="190" labelSize="32" paddingTb="20">
							<select-item v-model="form.people" :list='personList' @getSelect="getPerson"></select-item>
						</label-box>
						<label-box label="设置男女人数" labelWidth="190" labelSize="32" paddingTb="20"  v-if="mpeople.length">
							<select-item v-model="form.mpeople" :list="mpeople"></select-item>
						</label-box>
					</view>
				</item-box>
				<view class="u-font-32 box-title text-bold u-padding-bottom-24 u-margin-top-20">选择剧本标签</view>
				<!-- 第三步 -->
				<view v-for="(item,index) in thirdStepList" :key="index" class="u-margin-bottom-20">
					<select-items span="4" :item="item" v-model="item.checked" :key="item.id">
						<view slot="title"></view>
						<view slot="inner-title" class="inner-title u-font-28 box-title u-border-bottom">
							<text class="u-margin-left-20">{{item.cateName}}</text>
						</view>
					</select-items>
				</view>
			</template>
			<view class="u-margin-top-80 u-text-center">
				<view class="u-flex u-row-center">
					<view v-for="(num,index) in stepNum" :key="index" class="step-box u-position-relative" :class="{'step-active':index+1<=step }">
						<text class="step-num u-position-relative" @click="changeStep(index)"></text>
					</view>
				</view>
				<view class="box-title u-font-28 u-margin-top-30 u-margin-bottom-42">
					仅需3步，轻松上传剧本
				</view>
				<item-btn block height="88"  @click="saveStep" :loading="loading">{{step==3?'保存':'下一步'}}</item-btn>
			</view>
		</view>
		<edit-modal :show="addFlag" @close="close" :isCityEdit="true" v-model="activeForm" @remove="removeItem" @confirm="saveCity" isCity/>
	</view>
</template>

<script>
	import uploader from '@/components/upload/upload.vue'
	import {add,getDetail,getList,deleteIds } from '@/api/crud.js'
	import selectItems from '@/components/selectArr/selectArr.vue'
	import cityBtn from './button.vue'
	import editModal from './addCityPop/index.vue'
	import addCity from './addCity.js'
	import {editProductRelCity,editProductTempCity} from '@/api/city.js'
	export default {
		mixins:[addCity],
		data() {
			return {
				content: '',
				selectList: [],
				apiModule:"shopApi",
				customStyle:{
					background:'#E6E6E6',
					borderRadius:'17rpx',
					padding:'26rpx',
					color:'#333'
				},
				uploadFlag:true,
				step:1,
				stepNum:3,
				secondStepList:[],
				thirdStepList:[],
				personList:[],
				form:{},
				pushTypeChecked:[], //发行方式
				larpChecked:[], //剧本类型
				citySelectList:[], //城市选择
				mpeople:[], //男女人数
				acceptList:{
					children:[{
						cateName:'接受',
						id:1
					},{
						cateName:'不接受',
						id:0
					}]
				},
				loading:false,
				showCity:false,
				images:[],
				showUpload:true,
				option:{},
				addFlag:false,
				activeCity:null,
				activeForm:{},
				saveStepNum:1 //当前已经保存过的步骤
			}
		},
		computed: {
			isCityType() {
				return this.secondStepList[0]&&this.secondStepList[0].children.some(val=>this.pushTypeChecked.indexOf(val.id)!=-1&&['城限','独家'].includes(val.label)) 
			},
			activeType(){
				return this.secondStepList[0]&&this.secondStepList[0].children.find(val=>val.id==this.pushTypeChecked[0]) || {}
			},
			cityList(){
				return !this.showCity ? this.citySelectList.slice(0,6) : this.citySelectList
			},
			isEdit(){
				return !!this.option.productId
			},
			apiType(){
				return this.isEdit? 'product':'storeProductTemp'
			}
		},
		components: {
			uploader,selectItems,cityBtn,editModal
		},
		async onLoad(option) {
			await this.$store.dispatch('getClassify').then(res=>{
				this.thirdStepList = this.getFilterList(['剧本类别','剧本背景','剧本题材'],res).map(this.setChecked);
				this.secondStepList = this.getFilterList(['发行方式'],res);
				const {children} = this.getFilterList(['人数'],res)[0]
				this.personList = children.map(val=>({label:val.label,value:val.id}))
			})
			
			//编辑剧本
			if(option.productId){
				this.option = option;
				this.showUpload = false;
				this.saveStepNum = 3;
				await getDetail(option,this.apiType,this.apiModule,'findTempByProductId').then(res=>{
					this.form = res
					this.showUpload = true;
					this.setSelectTag()
					this.getList()
					//设置第三步的剧本类别条件
					const categorys = JSON.parse(this.form.categoryJson);
					this.thirdStepList = this.thirdStepList.map(val=>{
						const checked = categorys.find(item=>item.label===val.label);
						if(checked){
							const ids = checked.id.split(',').map(a=>Number(a));
							val.checked = ids;
						}
						return val;
					})
				})
				return false;
			}
			//获取历史的新增剧本记录
			getDetail('',this.apiType+'/getByUid',this.apiModule,this.$store.getters.loginForm.uid).then(res=>{
				this.form = res || {
					info:'',
					name:'',
					releaseTime:'',
					people:'',
					mpeople:'', 
					isAcceptCityOutside:1
				};
				this.setSelectTag()
				this.step = this.form.operationStep ? this.form.operationStep+1 : 1;
				this.saveStepNum = this.step;
			})
		},
		onShow() {
			this.getpushType()
		},
		methods: {
			setSelectTag(){
				if(!Array.isArray(this.form.isAcceptCityOutside)){
					this.form.isAcceptCityOutside = this.form.isAcceptCityOutside>-1 ? [this.form.isAcceptCityOutside] : [1];
				} //选中是否接受城限以外的剧本
				this.pushTypeChecked = [this.form.issueMode] //设置发行方式
			},
			//获取城市
			getList(){
				const obj = {
					issueMode:this.pushTypeChecked[0]
				}
				if(this.form.id) obj.productTempId = this.form.id 
				if(this.form.productId) obj.productId = this.form.productId;
				const name = this.isEdit ? 'getWaitUpdateCitys' : 'getCitys';
				getList(obj,this.apiType,this.apiModule,name).then(res=>{
					this.citySelectList = res;
				})
			},
			getpushType(val){
				this.isCityType&&this.getList()
			},
			getFilterList(filterArr,res) {
				return res.filter(val=>filterArr.includes(val.cateName))
			},
			setChecked(val){
				this.$set(val,'checked',[])
				return val;
			},
			addCityPath(){
				const item = this.secondStepList[0].children.find(val=>val.id==this.pushTypeChecked[0])
				this.updateCityList().then(res=>{
					const params = {
						id:this.form.id || this.option.productId,
						issueMode:this.pushTypeChecked[0],
						issueModeName:item.label,
						istemp: !this.isEdit ? 1 : 0 //是否为临时剧本 1为临时
					}
					if(this.form.id) params.productTempId = this.form.id
					if(this.form.productId) params.productId = this.form.productId;
					this.$u.route({
						url:"/pages/addLarp/addCity",
						params
					})
				})
				
			},
			//上传的图片
			getImgStr(str){
				this.form.sliderImage = str;
			},
			//监听上传图片
			getUpload(flag){
				this.uploadFlag = flag;
			},
			//更新城市
			updateCityList(){
				//更新城市数据
				const fn = this.isEdit ? editProductRelCity : editProductTempCity;
				const obj = {
					cityList:this.citySelectList
				}
				if(this.form.id) obj.productTempId = this.form.id
				if(this.form.productId) obj.productId = this.form.productId;
				return fn(obj); // 更新城市数据
			},
			//第一步验证
			step1(){
				const {name,info} = this.form;
				if(!name){
					this.$u.toast('请填写剧本名称')
					return false;
				}
				if(!info){
					this.$u.toast('请编辑剧本简介')
					return false;
				}
				if(!this.uploadFlag) {
					this.$u.toast('门店图片上传中')
					return false;
				}
				const {sliderImage} = this.form;
				if(!sliderImage){
					this.$u.toast('请至少上传一张剧本图片')
					return false;
				}
				return true;
			},
			//第二步验证
			step2(){
				const {issueMode,releaseTime} = this.form;
				if(this.pushTypeChecked.length===0){
					this.$u.toast('请选择发行方式')
					return false;
				}
				if(!releaseTime){
					this.$u.toast('请选择预计发行时间')
					return false;
				}
				if(this.isCityType&&this.citySelectList.length===0){
					this.$u.toast('请添加城市')
					return false;
				}
				this.updateCityList()
				return true;
			},
			//第三步验证
			step3(){
				if(this.mpeople.length===0){
					this.$u.toast('请选择剧本人数')
					return false;
				}
				if(!this.form.mpeople){
					this.$u.toast('请选择男女人数')
					return false;
				}
				const getUnSelect = this.thirdStepList.find(val=>val.checked.length===0)
				if(getUnSelect){
					this.$u.toast('请选择'+getUnSelect.cateName)
					return false;
				}
				return true;
				
			},
			//保存步骤
			saveStep1(obj){
				//obj.sliderImage = this.images;
				
				return obj
			},
			saveStep2(obj){
			  console.log(this.pushTypeChecked)
				obj.issueMode = this.pushTypeChecked[0] //发行方式
				if(this.isCityType) obj.cityJson = JSON.stringify(this.citySelectList); //如果不为盒装
				return obj
			},
			saveStep3(obj){
				const typeList = this.getTypeList();
				obj.categoryJson = JSON.stringify(typeList)
				obj.mpeople = obj.mpeople.replace('男','');
				obj.people = obj.people.replace('人','');
				return obj
			},
			saveStep(){
				const isComplete = this.step==3; //生成剧本
				if(!this[`step${this.step}`]()){
					return false;
				}
				let obj = {
					sliderImage:'',
					issueMode:'', 
					...this.form,
					operationStep:this.step,
					isComplete
				}
				obj = this[`saveStep${this.step}`](obj)
				obj.isAcceptCityOutside = obj.isAcceptCityOutside[0]
				//if(obj.releaseTime) obj.releaseTime+=' 00:00:00';
				const name = this.isEdit ? 'saveByTemp':'saveTemp'
				this.loading = true;
				
				add(obj,this.apiType,this.apiModule,name).then(res=>{
					this.form = {
						...obj,
						isAcceptCityOutside:[obj.isAcceptCityOutside]
					};
					this.form.id = res;
					this.loading = false;
					if(!isComplete){
						++this.step;
						this.saveStepNum = this.step;
						if(this.step===3){
							this.stepThirdData()
						}
						return false;
					}
					this.routeBack('保存成功')
				}).catch(()=>{
					this.loading = false;
				})
			},
			//获取选中的动态选项
			getTypeList(){
				return  this.thirdStepList.map(val=>{
					const checkArr = Array.isArray(val.check); //判断是否为多选
					const getCheckList = val.children.filter(item=>val.checked.includes(item.id))
					const name = getCheckList.map(val=>val.cateName).join(',')
					const id = getCheckList.map(val=>val.id).join(',')
					return {id,label:val.cateName,name}
				}).filter(val=>val.id)
			},
			//获取选择的剧本人数
			getPerson(arr){
				const item = arr[0];
				const num = item.label.replace('人','');
				const mpeople = [{
					label:'0男',
					value:0
				}];
				let i = 0;
				while(i<num){
					mpeople.push({
						label:`${i+1}男`,
						value:i+1
					})
					i++;
				}
				this.mpeople = mpeople
			},
			//修改步骤数
			changeStep(index){
				const currentClickNum = index+1;
				if(this.saveStepNum<currentClickNum){
					this.$u.toast('Oh NO')
					return false;
				}
				this.step = currentClickNum;
				this.stepThirdData()
			},
			//特定步骤组装特定数据 只有第三步才需要组装人数 其他都应该删除人数
			stepThirdData(){
				if(this.form.people){
					this.form.people = this.returnPersonStr('人',this.form.people)
				}
				if(this.form.mpeople){
					this.form.mpeople = this.returnPersonStr('男',this.form.mpeople)
				}
				if(this.step===3){
					//设置剧本人数
					this.getPerson([{
						label:this.form.people
					}])
				}
			},
			returnPersonStr(txt,numStr){
				numStr = `${numStr}`; //转换为字符串
				if(numStr) return this.step===3&&numStr.indexOf(txt) == -1 ? `${numStr}${txt}` : numStr.replace(txt,'')
				return ''
			}
		},
	}
</script>

<style lang="scss" scoped>
.max-length-txt{
	right:20rpx;
	bottom: 20rpx;
	text-align: right;
	margin-right: 20rpx;
}
.step-box{
	&:not(:last-child){
		padding-right: 100rpx;
		&::before{
			content: '';
			position: absolute;
			height: 4rpx;
			background-color: var(--background-second-color);
			right: 0;
			left: 0;
			top: 50%;
			margin-top:-4rpx;
		}
	}
	&.step-active{
		.step-num::after{
			content: '';
			position: absolute;
			width: 18rpx;
			height: 18rpx;
			border-radius: 50%;
			background-color: var(--theme-color);
			left: 50%;
			top: 50%;
			transform: translate(-50%,-50%);
		}
	}
}
.step-num{
	display: inline-block;
	width: 28rpx;
	height: 28rpx;
	background-color: var(--background-second-color);
	// border: 2rpx solid $primary;
	border-radius: 50%;
	// line-height: 40rpx;
	// font-size: 30rpx;
	// color: $primary;
	// margin: 0 50rpx;
}
.showFlag{
	background-color: rgb(118, 92, 254);
	text-align: center;
	line-height: 50rpx;
	color: white;
	border-radius: 50rpx;
	margin: 30rpx auto 0;
	width: 200rpx;
}
.inner-title{
	line-height: 60rpx;
}
.textarea-box{
	background: rgb(230, 230, 230);
  border-radius: 16rpx;
  padding: 0 0 26rpx 0;
  color: rgb(51, 51, 51);
}
</style>